<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Controller;

use Admin\Controller\AdminActionController;
use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Goods\Entity\Goods;
use Goods\Entity\GoodsSpecTag;
use Goods\Entity\GoodsSpecTagGoods;
use Goods\Service\GoodsSpecTagGoodsManager;
use Goods\Service\GoodsSpecTagManager;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;

class GoodsSpecTagController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $goodsSpecTagManager;
    private $goodsSpecTagGoodsManager;

    public function __construct(
        Translator $translator,
        EntityManager $entityManager,
        GoodsSpecTagManager $goodsSpecTagManager,
        GoodsSpecTagGoodsManager $goodsSpecTagGoodsManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
        $this->goodsSpecTagManager = $goodsSpecTagManager;
        $this->goodsSpecTagGoodsManager = $goodsSpecTagGoodsManager;
    }

    /**
     * 特定标签列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $mobileTemplateSpecTag  = Common::getDefaultTemplateTag('goodsSpecTag');
        $pcTemplateSpecTag      = Common::getDefaultTemplateTag('goodsSpecTag', 'pcTemplate');

        $specTagGoodsNumArray = [];
        $specTagList = $this->entityManager->getRepository(GoodsSpecTag::class)->findAllSpecTag(array_filter([Common::getDefaultTemplateCode(), Common::getDefaultTemplateCode('pcTemplate')]));
        if($specTagList) foreach ($specTagList as $specTagValue) {
            if(strpos($specTagValue[0]->getTemplateCode(), 'mobile-') !== false) $specTagGoodsNumArray['mobile'][$specTagValue[0]->getSpecTagCode()] = $specTagValue['goodsNum'];
            else $specTagGoodsNumArray['pc'][$specTagValue[0]->getSpecTagCode()] = $specTagValue['goodsNum'];
        }

        return [
            'mobileSpecTag'     => $mobileTemplateSpecTag,
            'pcSpecTag'         => $pcTemplateSpecTag,
            'specTagGoodsNum'   => $specTagGoodsNumArray
        ];
    }

    /**
     * 设置特定标签商品
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editSpecTagGoodsAction()
    {
        $specTag    = $this->request->getQuery('specTag', '');
        $specTagType= $this->request->getQuery('type');

        if(!in_array($specTagType, ['pc', 'mobile'])) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该标记的类型不存在!'));
            return $this->redirect()->toRoute('goods-spec-tag');
        }

        $goodsSpecTagArray = Common::getDefaultTemplateTag('goodsSpecTag', $specTagType.'Template');
        if(!isset($goodsSpecTagArray[$specTag])) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该标记不存在!'));
            return $this->redirect()->toRoute('goods-spec-tag');
        }

        $templateCode = $specTagType == 'mobile' ? Common::getDefaultTemplateCode() : Common::getDefaultTemplateCode('pcTemplate');

       $tagSort = stripos(implode(',', $goodsSpecTagArray), $goodsSpecTagArray[$specTag]);
        $specTagInfo = $this->entityManager->getRepository(GoodsSpecTag::class)->findOneBy(['specTagCode' => $specTag, 'templateCode' => $templateCode]);
        if($specTagInfo == null) {
            $specTagInfo = $this->goodsSpecTagManager->addSpecTag([
                'specTagName' => $goodsSpecTagArray[$specTag],
                'specTagCode' => $specTag,
                'specTagSort' => $tagSort,
                'templateCode'=> $templateCode
            ]);
        } elseif($specTagInfo->getSpecTagSort() != $tagSort) $specTagInfo = $this->goodsSpecTagManager->editSpecTag(['specTagSort' => $tagSort], $specTagInfo);

        $specTagGoodsList = $this->entityManager->getRepository(GoodsSpecTagGoods::class)->findSpecTagGoods($specTagInfo->getSpecTagId());

        return ['specTagInfo' => $specTagInfo, 'specTagGoodsList' => $specTagGoodsList];
    }

    /**
     * 添加单个特定标签商品
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addSpecTagGoodsAction()
    {
        $goodsId    = (int) $this->params()->fromPost('goodsId', -1);
        $specTagId  = (int) $this->params()->fromPost('specTagId', -1);
        $specTagCode= $this->params()->fromPost('specTagCode');
        $templateCode= $this->params()->fromPost('templateCode');

        $goodsInfo      = $this->entityManager->getRepository(Goods::class)->findOneByGoodsId($goodsId);
        $specTagInfo    = $this->entityManager->getRepository(GoodsSpecTag::class)->findOneBy(['specTagId' => $specTagId, 'specTagCode' => $specTagCode, 'templateCode' => $templateCode]);
        if($goodsInfo && $specTagInfo) {
            $specGoods = $this->entityManager->getRepository(GoodsSpecTagGoods::class)->findOneBy(['specTagId' => $specTagId, 'goodsId' => $goodsId, 'specTagCode' => $specTagCode, 'templateCode' => $templateCode]);
            if ($specGoods == null) {
                $addState = $this->goodsSpecTagGoodsManager->addSpecTagGoods(['specTagId' => $specTagId, 'goodsId' => $goodsId, 'specTagGoodsSort' => 255, 'specTagCode' => $specTagCode, 'templateCode' => $templateCode]);
                if($addState) {
                    return new JsonModel([
                        'state' => 'ok',
                        'result'=> [
                            'specTagGoodsId'    => $addState->getSpecTagGoodsId(),
                            'goodsId'           => $goodsId,
                            'goodsState'        => Common::goodsState($this->translator)[$goodsInfo->getGoodsState()],
                            'goodsName'         => $goodsInfo->getGoodsName(),
                            'specTagGoodsSort'  => 255
                        ]
                    ]);
                }
            }
        }
        return new JsonModel(['state' => 'error']);
    }

    /**
     * 更新特定标签商品
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function updateSpecTagGoodsAction()
    {
        $specTagGoodsId     = (int) $this->request->getPost('specTagGoodsId');
        $specTagGoodsSort   = (int) $this->request->getPost('specTagGoodsSort');

        $specTagGoodsInfo = $this->entityManager->getRepository(GoodsSpecTagGoods::class)->findOneBy(['specTagGoodsId' => $specTagGoodsId]);
        if($specTagGoodsInfo && $specTagGoodsSort > 0) {
            $this->goodsSpecTagGoodsManager->editSpecTagGoods(['specTagGoodsSort' => $specTagGoodsSort], $specTagGoodsInfo);
        }

        return new JsonModel(['message' => $this->translator->translate('更新完成')]);
    }

    /**
     * 批量设置特定标签排序
     * @return mixed
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     * @throws \Doctrine\Persistence\Mapping\MappingException
     */
    public function updateSpecTagGoodsAllSortAction()
    {
        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            if(!empty($data)) {
                $this->goodsSpecTagGoodsManager->updateSpecTagAllGoodsSort($data);
                $this->adminCommon()->addOperLog($this->translator->translate('批量排序处理成功!'), $this->translator->translate('特定商品标签'));
            }
        }
        return $this->adminCommon()->toReferer();
    }

    /**
     * 删除特定标签商品的某一个商品
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     */
    public function deleteSpecTagGoodsAction()
    {
        $specTagGoodsId = (int) $this->params()->fromRoute('id', -1);
        $specTagGoodsInfo = $this->entityManager->getRepository(GoodsSpecTagGoods::class)->findOneBy(['specTagGoodsId' => $specTagGoodsId]);
        if($specTagGoodsInfo == null) return new JsonModel(['msg' => $this->translator->translate('该标签商品不存')]);
        $this->goodsSpecTagGoodsManager->deleteSpecTagGoods($specTagGoodsInfo);

        return new JsonModel(['state' => 'ok']);
    }
}